package binding

import (
	"time"

	"gitee.com/go-errors/errors"
)

var ErrNoValue = errors.New("no value")

var timeLayouts = []string{
	time.RFC3339,
	time.RFC1123Z,
	time.RFC1123,
	time.RFC850,
	time.RFC822Z,
	time.RFC822,
	time.UnixDate,
}

var noTzLayout = []string{
	"2006/01/02 15:04:05",
	"2006/01/02 15:04",
	"2006/01/02",
	"2006-01-02 15:04:05",
	"2006-01-02 15:04",
	"2006-01-02",
	"20060102150405",
	"200601021504",
	"20060102",
}

func parseBool(s string) (b bool, err error) {
	if s == "" {
		err = errors.New("cannot parse bool from empty string")
		return
	}
	switch s {
	case "1", "t", "T", "true", "TRUE", "True", "on", "ON", "On", "yes", "Yes", "YES":
		b = true
	case "0", "f", "F", "false", "FALSE", "False", "off", "OFF", "Off", "no", "No", "NO":
		b = false
	default:
		err = errors.Errorf("cannot parse bool from %q", s)
	}
	return
}

func parseTime(s string) (t time.Time, err error) {
	if s == "" {
		err = errors.New("cannot parse time.Time from empty string")
		return
	}
	var ex error
	for _, layout := range timeLayouts {
		if t, ex = time.Parse(layout, s); ex == nil {
			err = nil
			return
		}
		err = errors.Multi(err, ex)
	}
	for _, layout := range noTzLayout {
		if t, ex = time.ParseInLocation(layout, s, time.Local); ex == nil {
			err = nil
			return
		}
		err = errors.Multi(err, ex)
	}
	return
}

func parseDuration(s string) (time.Duration, error) {
	if s == "" {
		return 0, errors.New("cannot parse time.Time from empty string")
	}
	d, err := time.ParseDuration(s)
	return d, errors.Wrap(err)
}

//func handleRecover(err *error) {
//	//if re := errors.Any(recover()); re != nil {
//	//	log.Printf("%+v", re)
//	//	*err = re
//	//}
//}
